package io.netty.client.server;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.client.core.AbstractNettyClient;
import io.netty.util.concurrent.ScheduledFuture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
public class connectScheduledTask extends ChannelInboundHandlerAdapter {
    private ScheduledFuture<?> scheduledFuture;
    private String ip;
    private String port;

    public connectScheduledTask() {
    }

    public connectScheduledTask(String ip, String port) {
        this.ip = ip;
        this.port = port;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        super.channelActive(ctx);
        if (scheduledFuture == null) {
            scheduledFuture = ctx.executor().scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    if (ctx.channel().isActive()) {
                        System.out.println("=======run======这里是Netty的定时任务===================");
                    }

                    if(!ctx.channel().isActive()){
                        scheduledFuture.cancel(true);
                    }
                    /**
                     * 即使关闭了客户端，这里仍然会运行
                     */
                    System.out.println("=============这里是Netty的定时任务===================");
                }
            }, 0, 3, TimeUnit.SECONDS);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String message = (String) msg;
        // 这里接收服务器返回的信息
        System.out.println("=====心跳接收到返回值=====" + message);
    }

    /**
     * 连接中断会在这里抛出异常，抛出异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        try {
            super.exceptionCaught(ctx, cause);
        } catch (IOException e) {
            // 对于 IOException，我们可以认为是连接中途断开，不需要关闭客户端，只需要打印出错日志即可
            System.out.println("--抛出异常连接中断--: " + e.getMessage());
        } finally {
            if (scheduledFuture != null) {
                scheduledFuture.cancel(true);
                scheduledFuture = null;
            }
            ctx.close();
        }
    }

}

